var express = require('express');
var router = express.Router();
var config = require("../config.js");
var OAuth = require('wechat-oauth');
var redis = require("redis");
var client = redis.createClient(config.redis.port, config.redis.ip);
client.auth(config.redis.password);
client.select(config.redis.database);

var Token = {
  getToken: function(openid, callback) {
    client.hget("openid_token", openid, function(err, responseGet) {
      if (err) {
        return callback(err);
      }
      else {
        return callback(null, JSON.parse(responseGet));
      }
    });
  },
  setToken: function(openid, token, callback) {
    client.hset("openid_token", openid, JSON.stringify(token), callback);
  }
}


var oauthApi = new OAuth(config.wechat.appid, config.wechat.appSecret, function(openid, callback) {
  Token.getToken(openid, callback);
}, function(openid, token, callback) {
  Token.setToken(openid, token, callback);
});


router.get('/getAuthorizeURL', function(req, res, next) {
  console.log('~~~~getAuthorizeURL:');
  var finalBase = req.query.finalbase;
  var redirectUrl = config.wechat.redirectBase + "/oauth/callback";
  var state = finalBase + req.query.state;
  var scope = "snsapi_userinfo";
  var url = oauthApi.getAuthorizeURL(redirectUrl, state, scope);
  res.redirect(url);
});

router.all('/callback', function(req, res, next) {
  console.log('~~~~callback:');
  var code = req.query.code;
  var state = req.query.state;

  /* 获取Openid和AccessToken */
  oauthApi.getAccessToken(code, function(err, result) {
    console.log(result);
    if (err) {
      res.render('error', err);
    }

    var accessToken = result.data.access_token;
    var openid = result.data.openid;

    /*获取用户信息*/
    oauthApi.getUser(openid, function(err, result) {
      if (err) {
        res.render('error', err);
      }

      if (state.indexOf("?") > 0) {
        state = state + "&openid=" + openid + "&access_token=" + accessToken;
      }
      else {
        state = state + "?openid=" + openid + "&access_token=" + accessToken;
      }
      result.finalUrl = state;
      res.redirect(state); //跳转至授权后的页面
    });
  });
});
module.exports = router;
